package club.dmyang.controller;

import club.dmyang.common.enums.RespCodeEnums;
import club.dmyang.common.vo.ArticleVo;
import club.dmyang.common.vo.ResposeVo;
import club.dmyang.entity.*;
import club.dmyang.service.ArticleService;
import club.dmyang.service.CarouselService;
import club.dmyang.service.CategoryService;
import club.dmyang.service.CommentService;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created by brss on 2017/7/20.
 */
@Controller
public class IndexController {
    @Autowired
    private ArticleService articleService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private CarouselService carouselService;

    @RequestMapping("/")
    public String defaultIndex(){
        return "redirect:index";
    }

    @RequestMapping("/index")
    public String index(@RequestParam(defaultValue = "1") Integer page,
                        @RequestParam(defaultValue = "10") Integer limit,
                        Model model){
        // 查询最新文章列表
        List<Article> articleList = articleService.findNewestArticlesByPageAndLimit(page, limit);
        //创建要返回给模版的List
        List<ArticleVo> articleVoList = new ArrayList<>();
        //查询每篇文章所属分类
        for (Article article : articleList) {
            Category c = categoryService.findByPrimaryKey(article.getCategoryId());
            ArticleVo articleVo = new ArticleVo();
            try {
                BeanUtils.copyProperties(articleVo,article);
            } catch (Exception e) {
                e.printStackTrace();
            }
            articleVo.setCategory(c.getCname());
            articleVoList.add(articleVo);
        }
        // 查询数据库中总文章数
        int allNums = articleService.findAllNums();
        // 查询carousel
        List<Carousel> carouselList = carouselService.findAll();
        model.addAttribute("articleVoList",articleVoList);//返回文章列表
        model.addAttribute("carouselList",carouselList);//录播列表
        model.addAttribute("allNums",allNums);//返回数据库总文章数目
        model.addAttribute("page",page);//返回当前页
        return "index";
    }

    /**
     * 文章详情页
     * 分页是针对评论而言的
     * @param aid
     * @param page
     * @param limit
     * @param model
     * @return
     */
    @RequestMapping("/details")
    public String details(Integer aid,
                          @RequestParam(defaultValue = "1") Integer page,
                          @RequestParam(defaultValue = "10") Integer limit,
                          Model model){
        //查询出文章
        ArticleWithBLOBs article = articleService.findOneArticle(aid);
        //查询文章分类
        Category category = categoryService.findByPrimaryKey(article.getCategoryId());
        //查询文章评论
        List<Comment> commentList = commentService.selectByArticleId(aid, page, limit);
        //查询文章评论总数
        int commentNums = commentService.selectNumsByArticleId(aid);
        //更新文章阅读量
        ArticleWithBLOBs a = new ArticleWithBLOBs();
        a.setAid(aid);
        a.setHits(article.getHits()+1);
        articleService.updateByPkSeletive(a);

        model.addAttribute("article", article);
        model.addAttribute("category", category);
        model.addAttribute("commentList", commentList);
        model.addAttribute("commentNums",commentNums);
        model.addAttribute("page",page);
        return "details";
    }

    /**
     * 列出留言板页
     * @param page
     * @param limit
     * @param model
     * @return
     */
    @RequestMapping("/message")
    public String message(@RequestParam(defaultValue = "1") Integer page,
                          @RequestParam(defaultValue = "10") Integer limit,
                          Model model){
        //分页前提下，按照时间排序，查询arti_id为-1的所有评论（-1表示不属于文章，属于首页留言板）
        int commentNums = commentService.selectNumsByArticleId(-1);
        List<Comment> commentList = commentService.selectByArticleId(-1, page, limit);

        model.addAttribute("commentList",commentList);
        model.addAttribute("page",page);
        model.addAttribute("commentNums",commentNums);

        return "message";
    }
    @RequestMapping("/search")
    public String search(Model model){
        model.addAttribute("allNums",0);//返回数据库总文章数目
        model.addAttribute("page",0);//返回数据库总文章数目
        return "search";
    }

    @RequestMapping("/archive")
    public String archive(Model model){

        Map<String, List<Article>> archiveMap = articleService.getArchive();
        model.addAttribute("archiveMap", archiveMap);
        return "archive";
    }

    /**
     * 按照分类id或标签id来查询文章列表
     * @param cid
     * @param page
     * @param limit
     * @param model
     * @return
     */
    @RequestMapping("/articlelist")
    public String articleList(Integer cid,
                              Integer tid,
                              @RequestParam(defaultValue = "1") Integer page,
                              @RequestParam(defaultValue = "10") Integer limit,
                              Model model){
        //文章列表
        List<Article> articleList = null;
        // 某分类或某标签下面的总文章数
        int allNums  = 0;
        //都为空时返回最新文章
        if ( cid == null && tid == null ){
            //查询最新文章
            articleList = articleService.findNewestArticlesByPageAndLimit(page,limit);
            allNums = articleService.findAllNums();
        }
        if ( cid != null ){
            //根据分类id查询
            articleList = articleService.findByCidWithPgAndLimit(cid, page, limit);
            allNums = articleService.findNumByCategoryId(cid);
        }else if ( tid != null ){
            //根据标签id查询
            articleList = articleService.findByTidWithPgAndLimit(tid, page, limit);
            allNums = articleService.findNumByTagId(cid);
        }
        //创建要返回给模版的List
        List<ArticleVo> articleVoList = new ArrayList<>();
        //查询每篇文章所属分类
        for (Article article : articleList) {
            Category c = categoryService.findByPrimaryKey(article.getCategoryId());
            ArticleVo articleVo = new ArticleVo();
            try {
                BeanUtils.copyProperties(articleVo,article);
            } catch (Exception e) {
                e.printStackTrace();
            }
            articleVo.setCategory(c.getCname());
            articleVoList.add(articleVo);
        }

        model.addAttribute("articleVoList",articleVoList);//返回文章列表
        model.addAttribute("allNums",allNums);//返回数据库总文章数目
        model.addAttribute("page",page);//返回当前页
        model.addAttribute("cid",cid);//返回当前页
        model.addAttribute("tid",tid);//返回当前页
        return "articlelist";
    }

    /**
     * 展示 关于页面
     * @param model
     * @return
     */
    @RequestMapping("/about")
    public String about(Model model){

        return "about";
    }

    @RequestMapping("/gosearch")
    public String goSearch(String keyword,
                           @RequestParam(defaultValue = "1") Integer page,
                           @RequestParam(defaultValue = "10") Integer limit,
                           Model model,
                           HttpServletRequest request){
        //获取Sessionid
        String sessionId = request.getSession().getId() + "_gosearch";
        if (redisTemplate.opsForValue().get(sessionId) != null){
            model.addAttribute("tip","5s内只允许搜索一次");//关键字
            model.addAttribute("page",1);//关键字
            model.addAttribute("allNums",0);//关键字
            model.addAttribute("keyword",keyword);//关键字
            return "search";
        }
        //把Sessionid装入redis，并且设置3秒过期
        redisTemplate.opsForValue().set(sessionId,sessionId,5, TimeUnit.SECONDS);

        List<Article> articleList = articleService.searchByKeyword(keyword, page, limit);
        Integer allNums = articleService.findNumByKeyword(keyword);
        model.addAttribute("articleList",articleList);//返回文章列表
        model.addAttribute("allNums",allNums);//返回数据库总文章数目
        model.addAttribute("page",page);//返回当前页
        model.addAttribute("keyword",keyword);//关键字
        return "search";
    }

    @RequestMapping("/error")
    public String error(){
        return "/common/error";
    }

    @RequestMapping("/getnotice")
    @ResponseBody
    public ResposeVo getNotices(){
        List<String> notices = null;
        try {
            notices = redisTemplate.opsForList().range("notice", 0, -1);
        } catch (Exception e) {
            e.printStackTrace();
            notices = new ArrayList<>();
            notices.add("欢迎访问本站，祝您生活愉快~万事如意，事事顺心");
            notices.add("梦想一旦被付诸行动，就会变得神圣。");
            notices.add("千磨万击还坚劲，任尔东西南北风。");
            notices.add("人之所以能，是相信能。");
            notices.add("过去属于死神，未来属于你自己。");
            notices.add("忘记昨天，直面今天，迎接明天。");
            notices.add("你认为自己是什么样的人，就将成为什么样的人。");
        }

        return new ResposeVo(RespCodeEnums.RESP_CODE_SUCC.getCode(),"查询成功",notices.size(),notices);
    }

}
